package com.flashcash.solu.view.presenter;

import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Pair;

import com.flashcash.kotlin.activity.PolicyDialogActivity;
import com.flashcash.solu.app.base.presenter.BaseActivityPresenterImpl;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.ProgressBean;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.view.IntroduceActivity;
import com.flashcash.solu.view.SplashActivity;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.documented.DocumentMessage;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 11:05
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class SplashActPresenterImpl extends BaseActivityPresenterImpl implements SplashActPresenter {
    private Long mStartTime;
    private Handler mHandler;

    public SplashActPresenterImpl() {
        mStartTime = SystemClock.currentThreadTimeMillis();
        mHandler = new Handler();
    }

    @Override
    public void disAttach() {
        super.disAttach();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }


    private void jumpToMainActivity(Long currentTime) {
        Long delayTime = (currentTime - mStartTime >= 1000L) ? 0 : (mStartTime + 1000 - currentTime);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isAttached()) {
                    DocumentMessage doc = DocumentMessage.Companion.getDoc();
                    Boolean aBoolean = doc.getBoolean(FieldParams.HAS_AGREED_THE_POLICY, false);
                    doc.reset();
                    if (aBoolean != null && aBoolean) {//已同意协议
                        if (isAttached()) {
                            //判断是否登录
                            if (((SplashActivity) mView).isLogin()) {//已登录，判断四步资料是否已填写完成
                                updateCertifyState();
                            } else {//未登录,跳转到介绍页
                                mView.getBaseActivity().startActivity(new Intent(mView.getBaseActivity(), IntroduceActivity.class));
                                try {
                                    mView.getBaseActivity().finish();
                                } catch (Throwable ignored) {
                                }
                            }
                        }
                    } else {//还没同意协议
                        Intent intent = new Intent(mView.getBaseActivity(), PolicyDialogActivity.class);
                        if (isAttached()) {
                            mView.getBaseActivity().startActivity(intent);
                        }
                        try {
                            mView.getBaseActivity().finish();
                        } catch (Throwable ignored) {
                        }
                    }
                }
            }
        }, delayTime);
    }

    @Override
    public void requestDataAndJump() {
        mStartTime = SystemClock.currentThreadTimeMillis();
        mHandler = new Handler();
        jumpToMainActivity(mStartTime);
    }

    @Override
    public void updateCertifyState() {
        mUserApi.progress(TokenManager.getInstance().getToken())
                .zipWith(mUserApi.getLatestLoanApp(TokenManager.getInstance().getToken(), "certifyFragment"), Pair::create)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Pair<ProgressBean, LatestLoanAppBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Pair<ProgressBean, LatestLoanAppBean> progressBeanLatestLoanAppBeanPair) {
                        if (progressBeanLatestLoanAppBeanPair.first != null) {
                            ((SplashActView) mView).updateCertifyStateSuccess(progressBeanLatestLoanAppBeanPair.first);
                            LatestLoanAppBean loanAppBean = progressBeanLatestLoanAppBeanPair.second;
                            boolean isEditable = false;
                            if (loanAppBean == null) {
                                isEditable = true;
                            } else {
                                String status = loanAppBean.getStatus();
                                if (TextUtils.equals(status, FieldParams.LoanStatus.CLOSED)
                                        || TextUtils.equals(status, FieldParams.LoanStatus.REJECTED)
                                        || TextUtils.equals(status, FieldParams.LoanStatus.PAID_OFF)
                                        || TextUtils.equals(status, FieldParams.LoanStatus.WITHDRAWN)
                                        || TextUtils.equals(status, FieldParams.LoanStatus.NOLOANAPP)) {
                                    isEditable = true;
                                }
                            }
                            CacheDataManage.INSTANCE.addData(FieldParamsInt.INFO_EDITABLE, isEditable);
                        }
                    }
                });
    }
}
